package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author mgx
 * @version 1.0
 * @date 2023/12/4 23:04
 * @desciption: 文件上传实现类
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient; // 注入minio操作客户端对象

    @Autowired
    private MinioConstantProperties props;

    /**
     * 文件上传
     *
     * @param file 上传文件
     * @return
     */
    @Override
    public String uploadImage(MultipartFile file) {
        try {
            // 1. 校验文件是否是图片 Nginx tomcat文件上传大小默认上限1M
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null) {
                throw new RuntimeException("图片格式非法！");
            }
            // 2. 拼接上传文件名, 生成图片唯一标识：/当日日期/uuid+文件名.后缀名
            String fileName = IdUtil.randomUUID();
            String folderName = DateUtil.today();
            String extName = FileUtil.extName(file.getOriginalFilename()); // 后缀名
            String objectName = "/" + folderName + "/" + fileName + "." + extName;
            // 3. 调用上传文件方法
            // Upload known sized input stream.
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(props.getBucketName()).object(objectName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            // 4. 返回图片url给前端
            return props.getEndpointUrl() + "/" + props.getBucketName() + objectName;
        } catch (Exception e) {
            log.error("[专辑服务]文件上传失败：{}", e);
            throw new RuntimeException("文件上传失败");
        }
    }
}
